# coding:utf-8

from pywpsrpc.rpcwpsapi import createWpsRpcInstance, wpsapi
from pywpsrpc.common import S_OK

FORMAT_DICT = {
    "doc": wpsapi.wdFormatDocument,
    "docx": wpsapi.wdFormatXMLDocument,
    "rtf": wpsapi.wdFormatRTF,
    "html": wpsapi.wdFormatHTML,
    "pdf": wpsapi.wdFormatPDF,
    "xml": wpsapi.wdFormatXML,

}
file_format_list = ["doc", "docx", "rtf", "html", "pdf", "xml"]


def down(request_property):
    file_path = request_property['input_path']
    convert_format = request_property['format']
    is_abort = request_property.get('abort', False)
    convert_to(file_path, convert_format, is_abort)


def convert_to(file_path, convert_format, abort_on_fails=False):
    result, rpc = createWpsRpcInstance()
    if result != S_OK:
        raise Exception('create the rpc instance is failed', result)
    result, app_word = rpc.getWpsApplication()
    try:
        if result != S_OK:
            raise Exception('get the application is failed', result)

        app_word.Visible = False     # close gui
        document = app_word.Documents
        result = convert_file(file_path, document, convert_format)
        if abort_on_fails and result != S_OK:
            raise Exception(f'{file_path} convert {convert_format} file is failed', result)
    finally:
        app_word.Quit()


def convert_file(file_path, document, convert_format):
    result, doc = document.Open(file_path, ReadOnly=True)
    if result != S_OK:
        return result
    new_file = f"{file_path.rsplit('.')[0]}.{convert_format}"
    result = doc.SaveAs2(new_file, FileFormat=FORMAT_DICT[convert_format])
    doc.Close(wpsapi.wdDoNotSaveChanges)
    return result


aaa = {
    'input_path': '/home/mjtree/文档/1.docx',
    'format': 'pdf',
}
down(aaa)


